package com.zhiwen.lockdemo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Auther: wuzhiwen
 * @Date: 2018/12/19 15:05
 * @Description:
 */
public class LunXunThread {
    public static void main(String[] args) {
        final Demo02 demo02 = new Demo02();
        new Thread(new Runnable() {
            public void run() {
                demo02.sysPrint1();
            }
        }, "A").start();
        new Thread(new Runnable() {
            public void run() {
                demo02.sysPrint2();
            }
        }, "B").start();
    }
}


class Demo02 {
    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    int i = 0;

    public void sysPrint1() {
        while (true) {
            lock.lock();
            try {
                if (i % 2 != 0) {
                    try {
                        condition1.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if (i > 10) {
                    break;
                }
                System.out.println(Thread.currentThread().getName() + "=====" + i);
                i++;
                condition2.signal();
            } finally {
                lock.unlock();
            }
        }
    }

    public void sysPrint2() {
        while (true) {
            lock.lock();
            try {
                if (i % 2 != 1) {
                    try {
                        condition2.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if (i > 10) {
                    break;
                }
                System.out.println(Thread.currentThread().getName() + "=====" + i);
                i++;
                condition1.signal();
            } finally {
                lock.unlock();
            }
        }
    }
}